<template>
  <div v-loading="loading" class="custom_field" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="onOpenAddField"> 添加字段 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="disableBatchBtn">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="updateBatchNetworkFieldStatus(false)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="updateBatchNetworkFieldStatus(true)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="onDelBatchField">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model.trim="listFieldSearch.name"
          placeholder="字段名称"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <div class="table_container">
      <el-table
        ref="tableDom"
        border
        stripe
        resizable
        :data="fieldData"
        height="100%"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="40" fixed="left" :align="'center'" />
        <el-table-column
          show-overflow-tooltip
          type="index"
          label="序号"
          width="50"
          :align="'center'"
          fixed="left"
        />
        <el-table-column show-overflow-tooltip prop="name" label="字段名称" width="200" />
        <el-table-column show-overflow-tooltip prop="type" label="字段类型" width="75">
          <template #default="{ row }">
            {{ getFieldTypeText(row.type) }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="content" label="字段内容" min-width="200" />
        <el-table-column show-overflow-tooltip prop="tip" label="提示信息" width="150" />
        <el-table-column prop="uploadSize" label="最大尺寸" width="75">
          <template #default="i">
            <span v-if="i.row.type == 5 || i.row.type == 6 || i.row.type == 7">{{
              i.row.uploadSize
            }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="uploadQty" label="上传数量" width="75">
          <template #default="i">
            <span v-if="i.row.type == 5 || i.row.type == 6 || i.row.type == 7">{{
              i.row.uploadQty
            }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="required" label="是否必填" width="75">
          <template #default="scope">
            <span v-if="scope.row.required">必填</span>
            <span v-if="!scope.row.required">选填</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="150" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="150" />
        <el-table-column prop="status" fixed="right" label="状态" width="70" :align="'center'">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="!scope.row.status">启用</HStatus>
              <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90" fixed="right">
          <template #default="scope">
            <h-space>
              <HLink @click="onOpenEditField(scope.row)">编辑</HLink>
              <h-link type="error" @click="handleDelCustomField(scope.row)">删除</h-link>
            </h-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <div class="pagination">
      <Pagination
        ref="pagingtion"
        :list_total="fieldTotal"
        @size-change="getList"
        @current-change="getList(false)"
      />
    </div>
    <!-- 添加/编辑  字段弹窗 -->
    <SelfDefinedTow
      :title="fieldTitle"
      :type="1"
      :is-open="networkFieldDialog"
      :field-vo="networkFieldVo"
      :is-show-del-btn="false"
      :loading="fieldLoading"
      @on-delete="delNetworkFieldApi($event)"
      @on-save="saveApi($event)"
      @on-close="networkFieldDialog = false"
    />
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, watch, onMounted } from 'vue'
  import { Search, Warning, Delete, CircleCheck, ArrowDown } from '@element-plus/icons-vue'
  import { Action, ElMessage, ElMessageBox, TableInstance } from 'element-plus'
  import { fieldSave, fieldGetList, fieldGetdetail, fieldDisalbe, fieldDelete } from '@/api/basic'
  import SelfDefinedTow from '@/components/SelfDefined/index2.vue'
  import { CustomField } from './types'

  const tableDom = ref<TableInstance | null>(null)
  const handleDelCustomField = (customField: CustomField) => {
    if (tableDom.value) {
      tableDom.value.clearSelection()
      tableDom.value.toggleRowSelection(customField, true)
      onDelBatchField()
    }
  }

  const disableBatchBtn = ref(true) // 是否禁用批量操作按钮，默认禁用
  const loading = ref(false) // 加载动画
  const fieldLoading = ref(false) // 保存字段加载动画
  const listFieldSearch = ref({
    // 搜索条件
    page: 1,
    limit: 50,
    name: '',
  })
  // 字段对象
  const networkFieldVo = ref({
    id: '',
    name: '',
    type: 1,
    required: false,
    status: false,
    tip: '请输入',
    uploadQty: 1,
    uploadSize: 100,
    mobileShow: true, // 是否移动端显示 false-不显示，true-是,示例值(true)
    contentVos: [{ id: '', val: '' }], // 单选/多选内容
    delContentIds: [], // 删除的单选/多选内容ID
  })
  const networkFieldDialog = ref(false) // 字段弹窗
  const fieldTitle = ref('') // 新增/修改字段弹窗
  const fieldTotal = ref() // 总数目
  const fieldData = ref([]) // 表格数据
  const pagingtion = ref() // 分页Dom
  const selectFieldIds = ref([]) // 列表选中的字段ID
  // 列表选中列事件
  const handleChange = (val: any[]) => {
    selectFieldIds.value = []
    val.forEach((item) => {
      selectFieldIds.value.push(item.id)
    })
  }

  // 清除列表选中列事件
  const clearTableSelection = () => {
    if (tableDom.value) {
      tableDom.value.clearSelection()
      selectFieldIds.value = []
    }
  }

  // 初始化字段值
  const initField = () => {
    networkFieldVo.value = {
      id: '',
      name: '',
      type: 1,
      required: false,
      status: false,
      tip: '请输入',
      uploadQty: 1,
      uploadSize: 100,
      mobileShow: true,
      contentVos: [{ id: '', val: '' }],
      delContentIds: [],
    }
  }

  // 打开新增字段弹窗
  const onOpenAddField = () => {
    networkFieldDialog.value = true
    fieldTitle.value = '添加工单自定义字段'
    initField()
  }

  // 打开编辑字段弹窗
  const onOpenEditField = async (obj: any) => {
    fieldTitle.value = '编辑工单自定义字段'
    initField()
    fieldLoading.value = true
    await fieldGetdetail(obj.id).then((res) => {
      fieldLoading.value = false
      networkFieldVo.value = res.data.data.row
      networkFieldDialog.value = true
    })
  }

  // 批量启用或禁用字段状态
  const updateBatchNetworkFieldStatus = (status: boolean) => {
    ElMessageBox({
      type: 'warning',
      title: '提示',
      message: `确定${status ? '禁用' : '启用'}勾选的字段? ${
        status ? '禁用后将不可被其他应用关联使用' : '启用后将被其他应用关联使用'
      }`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = `${status ? '禁用' : '启用'}中...`
          setTimeout(() => {
            done()
            updateNetworkFieldStatusApi(status)
            instance.confirmButtonLoading = false
          }, 100)
        } else {
          done()
        }
      },
    }).catch(() => {
      // 不可删除该注释，否则会引起报错
    })
  }

  // 批量删除字段
  const onDelBatchField = () => {
    ElMessageBox({
      type: 'error',
      title: '提示',
      message: '确定删除选中的字段? 删除后将不可恢复',
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action: Action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          delNetworkFieldApi(selectFieldIds.value).then(() => {
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            done()
          })
        } else {
          done()
        }
      },
    }).catch(() => {
      // 不可删除该注释，否则会引起报错
    })
  }

  // 请求启用或禁用字段状态
  const updateNetworkFieldStatusApi = (status: boolean) => {
    fieldDisalbe(selectFieldIds.value, status).then((res) => {
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      if (res.data.success) {
        getList()
        clearTableSelection()
      }
    })
  }

  // 请求删除字段Api
  const delNetworkFieldApi = async (arr) => {
    await fieldDelete(arr).then((res) => {
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      if (res.data.success) {
        networkFieldDialog.value = false
        getList()
        clearTableSelection()
      }
    })
  }

  // 请求保存字段Api
  const saveApi = async (e) => {
    networkFieldVo.value = e
    fieldLoading.value = true
    await fieldSave(networkFieldVo.value).then((res) => {
      fieldLoading.value = false
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      if (res.data.success) {
        networkFieldDialog.value = false
        initField()
        getList()
      }
    })
  }

  // 请求列表数据Api
  const getList = async (val = true) => {
    loading.value = true
    if (val) pagingtion.value.setPage()
    listFieldSearch.value.page = pagingtion.value.current
    listFieldSearch.value.limit = pagingtion.value.size
    await fieldGetList(listFieldSearch.value).then((res) => {
      loading.value = false
      fieldData.value = res.data.data.rows
      fieldTotal.value = parseInt(res.data.data.total)
    })
  }

  /**
   * 根据字段类型获取对应的文本
   * @param {Number} type - 字段类型
   */
  const getFieldTypeText = (type: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10) => {
    if (type === 1) {
      return '文本'
    }

    if (type === 2) {
      return '多行文本'
    }

    if (type === 3) {
      return '单选'
    }

    if (type === 4) {
      return '多选'
    }

    if (type === 5) {
      return '多图'
    }

    if (type === 6) {
      return '附件'
    }

    if (type === 7) {
      return '视频'
    }

    if (type === 8) {
      return '评分'
    }

    if (type === 9) {
      return '日期'
    }

    if (type === 10) {
      return '日期时间'
    }
  }

  // 监听列表选中的字段
  watch(
    () => selectFieldIds.value,
    () => {
      disableBatchBtn.value = true
      if (selectFieldIds.value.length > 0) {
        disableBatchBtn.value = false
      }
    },
  )
  onMounted(() => {
    getList()
  })
  // 返回方法
  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
